package cn.com.demo.keystore;

import cn.com.demo.cert.X509CertificateExample;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.security.auth.x500.X500PrivateCredential;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class JKSKeystoreExample {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static char[] password = "5751A28AC5F78387".toCharArray();

    public static KeyStore createKeyStore() throws Exception {
        KeyStore store = KeyStore.getInstance("JKS");
        //initialize
        store.load(null, null);

        X500PrivateCredential rootCredential = X509CertificateExample.generateRootCredetial();
        FileOutputStream fos = new FileOutputStream("D:/root.cer");
        fos.write(rootCredential.getCertificate().getEncoded());
        fos.close();
        X500PrivateCredential interCredential = X509CertificateExample.generateIntermediateCredential(
                rootCredential.getPrivateKey(), rootCredential.getCertificate());
        fos = new FileOutputStream("D:/inter.cer");
        fos.write(interCredential.getCertificate().getEncoded());
        fos.close();
		/*X500PrivateCredential endCredential = X509CertificateExample.generateEndCredential(interCredential.getPrivateKey(), 
				interCredential.getCertificate());*/

        X509Certificate[] chain = new X509Certificate[2];
//		chain[0] = endCredential.getCertificate();
        chain[0] = interCredential.getCertificate();
        chain[1] = rootCredential.getCertificate();

        //set the entries
        store.setCertificateEntry(rootCredential.getAlias(), rootCredential.getCertificate());
        store.setKeyEntry(interCredential.getAlias(), interCredential.getPrivateKey(), password, chain);


        return store;
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        KeyStore store = createKeyStore();
        char[] storePassword = "5751A28AC5F78387".toCharArray();

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        //save the store
        store.store(bOut, storePassword);
        FileOutputStream fos = new FileOutputStream(new File("D:/bjcaTest.jks"));
        fos.write(bOut.toByteArray());
        fos.close();
        bOut.close();
        //reload from scratch
        store = KeyStore.getInstance("JKS");
        store.load(new ByteArrayInputStream(bOut.toByteArray()), storePassword);

        Enumeration<String> e = store.aliases();
        while (e.hasMoreElements()) {
            String alias = (String) e.nextElement();
            System.out.println("found " + alias + ", isCertificate ? " +
                    store.isCertificateEntry(alias));
        }
    }

}
